package com.shujia.stream

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}

object Demo5RDDtoDS {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .master("local[2]")
      .appName("stream")
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()

    import spark.implicits._

    val sc: SparkContext = spark.sparkContext

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
      *
      * 将DS 转换成rdd之后，rdd没有有状态算子，不能进行全局累加
      * transform： 将DS 转换成RDD,使用rdd的api ,处理完之后返回一个新的rdd
      *
      */

    val tfDS: DStream[(String, Int)] = linesDS.transform((rdd: RDD[String]) => {


      val countRDD: RDD[(String, Int)] = rdd
        .flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)

      //返回一个rdd,的到一个新的DS
      countRDD
    })

    tfDS.print()

    ssc.start()
    ssc.awaitTermination()
    ssc.stop()


  }

}
